package com.huayal.mall.product.service.impl;

import com.huayal.common.constant.ProductConstant;
import com.huayal.mall.product.entity.AttrAttrgroupRelationEntity;
import com.huayal.mall.product.entity.AttrGroupEntity;
import com.huayal.mall.product.service.AttrAttrgroupRelationService;
import com.huayal.mall.product.service.AttrGroupService;
import com.huayal.mall.product.service.CategoryService;
import com.huayal.mall.product.vo.Attr;
import com.huayal.mall.product.vo.AttrResponseVo;
import com.huayal.mall.product.vo.AttrVo;
import lombok.extern.log4j.Log4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huayal.common.utils.PageUtils;
import com.huayal.common.utils.Query;

import com.huayal.mall.product.dao.AttrDao;
import com.huayal.mall.product.entity.AttrEntity;
import com.huayal.mall.product.service.AttrService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    AttrAttrgroupRelationService attrAttrgroupRelationService;

    @Autowired
    AttrGroupService attrGroupService;

    @Autowired
    CategoryService categoryService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageBase(Map<String, Object> params, Long catId, String attrType) {

        int attr_type="base".equals(attrType)?1:0;

        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("attr_type",attr_type);

        //有catId
        if (catId!=0){
            wrapper.eq("catelog_id",catId);
        }
        //有key
        String key = (String)params.get("key");
        if (StringUtils.isNotEmpty(key)){
           wrapper.and((w)->{
              w.eq("attr_id",key).or().like("attr_name",key);
           });
        }

        //分页
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                wrapper
        );


        PageUtils pageUtils = new PageUtils(page);
        //获取所属分类和所属分组数据
        List<AttrEntity> records = page.getRecords();
        List<AttrResponseVo> list = records.stream().map(attrEntity -> {
            AttrResponseVo attrResponseVo = new AttrResponseVo();
            BeanUtils.copyProperties(attrEntity, attrResponseVo);

            if (attr_type== ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()){
                QueryWrapper<AttrAttrgroupRelationEntity> attrAttrgroupRelationEntityQueryWrapper = new QueryWrapper<>();
                attrAttrgroupRelationEntityQueryWrapper.eq("attr_id", attrEntity.getAttrId());
                AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = attrAttrgroupRelationService.getBaseMapper().selectOne(attrAttrgroupRelationEntityQueryWrapper);
                if (attrAttrgroupRelationEntity != null && attrAttrgroupRelationEntity.getAttrGroupId() != null) {
                    AttrGroupEntity attrGroupEntity = attrGroupService.getById(attrAttrgroupRelationEntity.getAttrGroupId());
                    if (attrGroupEntity!=null)attrResponseVo.setGroupName(attrGroupEntity.getAttrGroupName());

                }
            }

            if (attrEntity.getCatelogId() != null) {
                attrResponseVo.setCatelogName(categoryService.getBaseMapper().selectById(attrEntity.getCatelogId()).getName());
            }

            return attrResponseVo;
        }).collect(Collectors.toList());
        pageUtils.setList(list);

        return pageUtils;
    }

    @Override
    public void saveAttr(AttrVo attr) {

        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr,attrEntity);
        this.save(attrEntity);

        if (attr.getAttrGroupId()!=null&&attr.getAttrType()==ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()){
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            attrAttrgroupRelationEntity.setAttrId(attrEntity.getAttrId());
            attrAttrgroupRelationEntity.setAttrGroupId(attr.getAttrGroupId());
            attrAttrgroupRelationService.save(attrAttrgroupRelationEntity);
        }

    }

    @Override
    public AttrResponseVo getAttrInfo(Long attrId) {

        AttrResponseVo attrResponseVo = new AttrResponseVo();
        AttrEntity attrEntity = this.baseMapper.selectById(attrId);
        BeanUtils.copyProperties(attrEntity,attrResponseVo);

        attrResponseVo.setCatelogPath(categoryService.getCatIds(attrEntity.getCatelogId()));

        if (attrEntity.getAttrType()==ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()){
            QueryWrapper<AttrAttrgroupRelationEntity> attrAttrgroupRelationEntityQueryWrapper = new QueryWrapper<>();
            attrAttrgroupRelationEntityQueryWrapper.eq("attr_id",attrEntity.getAttrId());
            attrResponseVo.setAttrGroupId(attrAttrgroupRelationService.getBaseMapper().selectOne(attrAttrgroupRelationEntityQueryWrapper).getAttrGroupId());
        }

        return attrResponseVo;
    }

    @Transactional
    @Override
    public void updateDetail(AttrVo attr) {

        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr,attrEntity);
        this.baseMapper.updateById(attrEntity);

        if (attrEntity.getAttrType()==ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()){
            QueryWrapper<AttrAttrgroupRelationEntity> attrAttrgroupRelationEntityQueryWrapper = new QueryWrapper<>();
            attrAttrgroupRelationEntityQueryWrapper.eq("attr_id",attr.getAttrId());
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = attrAttrgroupRelationService.getBaseMapper().selectOne(attrAttrgroupRelationEntityQueryWrapper);

            if (attrAttrgroupRelationEntity!=null){
                attrAttrgroupRelationEntity.setAttrGroupId(attr.getAttrGroupId());
                attrAttrgroupRelationService.update(attrAttrgroupRelationEntity,attrAttrgroupRelationEntityQueryWrapper);
            }else {
                attrAttrgroupRelationEntity.setAttrId(attr.getAttrId());
                attrAttrgroupRelationEntity.setAttrGroupId(attr.getAttrGroupId());
                attrAttrgroupRelationService.getBaseMapper().insert(attrAttrgroupRelationEntity);
            }
        }


    }


    @Override
    public void removeByIdsDetail(List<Long> asList) {
        for (Long id: asList) {
            QueryWrapper<AttrAttrgroupRelationEntity> attrAttrgroupRelationEntityQueryWrapper = new QueryWrapper<>();
            attrAttrgroupRelationEntityQueryWrapper.eq("attr_id",id);
            attrAttrgroupRelationService.getBaseMapper().delete(attrAttrgroupRelationEntityQueryWrapper);
        }

        this.baseMapper.deleteBatchIds(asList);
    }

    @Override
    public List<AttrEntity> getRelationAttr(Long attrGroupId) {

        List<AttrAttrgroupRelationEntity> list = attrAttrgroupRelationService.getBaseMapper().selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrGroupId));
        List<AttrEntity> attrEntities = list.stream().map(attrAttrgroupRelationEntity -> this.baseMapper.selectById(attrAttrgroupRelationEntity.getAttrId())).collect(Collectors.toList());
        return attrEntities;
    }

    @Override
    public PageUtils getNoAttrRelation(Map<String, Object> params, Long attrGroupId) {

        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<>();
        AttrGroupEntity attrGroup = attrGroupService.getById(attrGroupId);
        wrapper.eq("catelog_id",attrGroup.getCatelogId());
        wrapper.eq("attr_type",ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode());

        List<AttrAttrgroupRelationEntity> list = attrAttrgroupRelationService.getBaseMapper().selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrGroupId));
        List<Long> attrIds = list.stream().map(en -> en.getAttrId()).collect(Collectors.toList());
        if (attrIds.size()!=0){
            wrapper.notIn("attr_id",attrIds) ;
        }

        //key的操作
        String key = (String)params.get("key");
        if (key!=null&&!"".equals(key)){
           wrapper.and((w)->{
               w.eq("attr_id",key).or().like("attr_name",key);
           });
        }


        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public List<Attr> getAttrInfos(Long catalogId) {

        return this.baseMapper.getAttrInfosByCateId(catalogId);
    }


}